package com.lora.communication.mqtt;

import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * mqtt主题管理类，可以通过此类创建mqtt服务,并订阅主题
 */
@Component
public class LoraTopicManager {
    private final Logger logger = LoggerFactory.getLogger(LoraTopicManager.class);
    @Autowired
    private MqttConnectUtil mqttConnectUtill;
    /**
     * 创建mqtt服务实例并订阅主题
     * 根据维传的主题订阅，格式为:application/0000000000000001/node/#
     * @param topic
     */
    public void subscribe(String topic){
        MqttClient mqttClient = mqttConnectUtill.getMqttClient();
        if(mqttClient!=null) {
            logger.info("mqtt主题监听队列已启动");
            try {
                while (!MqttThreadControlVariable.isClose) {
                    mqttClient.subscribe(topic);
                }
            } catch (MqttException e) {
                e.printStackTrace();
            }
        }
        logger.info("mqtt主题监听队列已关闭");
        try {
            Thread.sleep(20000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        subscribe("application/#");
    }

    public void sentMessage(String topic, String message) {
        MqttClient mqttClient = mqttConnectUtill.getMqttClient();
        if (mqttClient != null&&mqttClient.isConnected()) {
            try {
                MqttMessage mqttMessage = new MqttMessage();
                mqttMessage.setQos(2);
                mqttMessage.setPayload(message.getBytes());
                mqttClient.publish(topic, mqttMessage);
                logger.info("消息发送:" + message);
            } catch (MqttException e) {
                e.printStackTrace();
            }
        } else {
            logger.info("mqtt主题监听队列已关闭");
        }
    }
}
